package com.btm.dorisinfo.mcp;

import com.btm.dorisinfo.config.DynamicalConstant;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.model.Searchable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;


@Slf4j
@Component
public class DorisInfoMcpServer {

    private final Client meiliSearchClient;
    private final DynamicalConstant dynamicalConstant;
    private final ObjectMapper objectMapper;

    public DorisInfoMcpServer(Client meiliSearchClient, DynamicalConstant dynamicalConstant, ObjectMapper objectMapper) {
        this.meiliSearchClient = meiliSearchClient;
        this.dynamicalConstant = dynamicalConstant;
        this.objectMapper = objectMapper;
    }

    /**
     * 根据关键词搜索表结构信息
     * @param keyword 搜索关键词
     * @return 搜索结果（Markdown表格格式）
     */
    @Tool(description = "根据关键词搜索表结构信息")
    public String searchTableStructure(String keyword) {
        log.info("接收到搜索表结构请求，关键词：{}", keyword);
        try {
            // 获取MeiliSearch索引
            Index index = meiliSearchClient.index(dynamicalConstant.indexName);

            // 创建搜索请求
            SearchRequest searchRequest = new SearchRequest(keyword)
                    .setLimit(5);  // 限制返回结果数量
            
            // 执行搜索
            Searchable searchResult = index.search(searchRequest);
            // 查询命中的数据
            ArrayList<HashMap<String, Object>> hits = searchResult.getHits();
//            List<String> tableList = new ArrayList<>(hits.size() + 1);
            // 拼接成markdown的形式
//            for (HashMap<String, Object> hit : hits) {
//                List<Map<String, Object>> columns = (List<Map<String, Object>>) hit.get("columns");
//                String tableInfo = "# 表：" + hit.get("tableName") + "(" +hit.get("tableComment") + ")\n";
//                if (!CollectionUtils.isEmpty(columns)) {
//                    tableInfo += "## 字段：\n";
//                    for (Map<String, Object> column : columns) {
//                        tableInfo += "### ：" + column.get("columnName") + "\n - 注释：" + column.get("columnComment") + "\n - 数据类型：" + column.get("dataType") + "\n";
//                    }
//                }
//                tableList.add(tableInfo);
//            }
//            String resultJson = StringUtils.collectionToDelimitedString(tableList, "\n");
            // 拼接成表格的形式
            String tableInfo = "| 表名 | 表注释 | 字段名 | 字段注释 | 字段数据类型 | \n" +
                    "| --- | --- | --- | --- | --- | \n";
            for (HashMap<String, Object> hit : hits) {
                List<Map<String, Object>> columns = (List<Map<String, Object>>) hit.get("columns");
                if (!CollectionUtils.isEmpty(columns)) {
                    String tableName = (String) hit.get("tableName");
                    String tableDesc = (String) hit.get("tableComment");
                    for (Map<String, Object> column : columns) {
                        tableInfo += "| " + tableName  + " | " + tableDesc + " | " + column.get("columnName") + " | " + column.get("columnComment") + " | " + column.get("dataType") + " |\n";
                    }
                }
            }
            String resultJson = tableInfo;
            if (resultJson == null || resultJson.isEmpty()) {
                return "未找到匹配的表结构信息";
            } else {
                log.info("搜索结果: {}", resultJson);
//                log.info("查询关键词[{}]得到的表有{}", keyword, hits.stream().map(hit -> (String) hit.get("tableName")).toList());
            }
            // 在结果的开头，拼接上关键提示词
            return resultJson;
        } catch (Exception e) {
            log.error("搜索表结构出错: {}", e.getMessage(), e);
            return "搜索表结构出错: " + e.getMessage();
        }
    }
}